package ca.ets.osgi.hotelservice;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class HotelReader {
	
	private ListHotels lh;
	
	/**
	 * CONTRUCTOR
	 */
	public HotelReader(){}
	
	
	/**
	 * Make the list of hotels
	 */
	public void openList(){
		System.out.println("The system will try to make the list");
		try {
			lh = ListHotels.getInstance();
			File fXmlFile = new File("C://temp/ca.ets.osgi.hotelservice/src/ca/ets/osgi/hotelservice/hotel.xml");
			//File fXmlFile = new File("/eclipse/Workspace/ca.ets.osgi.hotelservice/src/ca/ets/osgi/hotelservice/hotel.xml");
    		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(fXmlFile);
			doc.getDocumentElement().normalize();
			NodeList nodes = doc.getElementsByTagName("Hotel");
			int num = nodes.getLength();
			for (int i = 0; i < nodes.getLength(); i++) {
				Node node = nodes.item(i);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					Element element = (Element) node;
					HotelInfo hotel = new HotelInfo();
					hotel.setHotelID(element.getAttribute("hid").trim());
					hotel.setPhone(getValue("phone",element).trim());
					hotel.setHotelName(getValue("nom",element).trim());
					
					Adresse adr = new Adresse();
					adr.setAdresseNum(Integer.parseInt(getValue("noadresse",element).trim()));
					adr.setRue(getValue("rue",element).trim());
					adr.setVille(getValue("ville",element).trim());
					adr.setProvince(getValue("province",element).trim());
					adr.setCodePostal(getValue("codepostal",element).trim());
					
					hotel.setAdresse(adr);
					hotel.setAvailablePlace(Integer.parseInt(getValue("place",element).trim()));
					hotel.setAvailability();
					hotel.setDateStart(getValue("dateStr",element).trim());
					hotel.setDateEnd(getValue("dateEnd",element).trim());
					
					HotelAbs ha = hotel;
					lh.addHotelToList(hotel.getHotelID(), ha);
				}
			}
			System.out.println("The list of hotels have been loaded");
			
			
		}catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private static String getValue(String tag, Element element) {
		NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
		Node node = (Node) nodes.item(0);
		return node.getNodeValue();
	}

}
